import { useEffect, useRef, useCallback } from 'react'
import { useAIAssist } from '@/hooks/useAIAssist'
import { useAutoReply } from '@/hooks/useAutoReply'
import { useAIChatStore } from '@/hooks/useAIChat'
import type { ProviderConfig, LiveStreamConfigPreset, AIProvider } from '@/hooks/useAIChat'
import { useAccounts } from '@/hooks/useAccounts'
import { createFrontendLogger } from '@/utils/logger'
import { IPC_CHANNELS } from 'shared/ipcChannels'

/**
 * AI智能回复服务组件
 * 定时检测评论列表，匹配关键词后使用AI生成语音回复
 */
export function SmartReplyService() {
  const { config } = useAIAssist()
  const { isListening, comments } = useAutoReply()
  const { currentAccountId } = useAccounts()
  const aiApiKeys = useAIChatStore((state): Record<AIProvider, string> => state.apiKeys)
  const aiConfig = useAIChatStore((state): ProviderConfig => state.config)
  const customBaseURL = useAIChatStore((state): string => state.customBaseURL)
  const liveStreamConfigs = useAIChatStore((state): LiveStreamConfigPreset[] => state.liveStreamConfigs)
  const activeLiveStreamConfigId = useAIChatStore((state): string | null => state.activeLiveStreamConfigId)
  
  const logger = useRef(createFrontendLogger('AI智能回复')).current
  const checkTimerRef = useRef<NodeJS.Timeout | null>(null)
  
  // 记录已回复的用户 Map<nick_name, timestamp>
  const repliedUsersRef = useRef<Map<string, number>>(new Map())
  // 记录已回复的问题 Map<nick_name_question, timestamp> 用于同一用户同一问题的防重复
  const repliedQuestionsRef = useRef<Map<string, number>>(new Map())
  // 记录最后处理的评论ID，避免重复处理
  const lastProcessedCommentIdRef = useRef<string>('')

  // 获取当前激活的直播配置
  const activeLiveStreamConfig = liveStreamConfigs?.find(
    (cfg: LiveStreamConfigPreset) => cfg.id === activeLiveStreamConfigId
  )

  // 智能回复检测函数
  const checkAndReply = useCallback(async () => {
    console.log(`[AI智能回复] ⏰ 开始检查评论列表，当前评论数: ${comments.length}`)
    
    if (!config.smartReply?.enable) return
    if (isListening !== 'listening') return
    if (!config.smartReply.keywords || config.smartReply.keywords.length === 0) return

    // 获取评论类型的消息
    const commentMessages = comments.filter(msg => msg.msg_type === 'comment')
    console.log(`[AI智能回复] 📝 评论消息数: ${commentMessages.length}`)
    
    if (commentMessages.length === 0) {
      console.log(`[AI智能回复] ⏭️  无评论，跳过检查`)
      return
    }

    // 获取最新的评论
    const latestComment = commentMessages[commentMessages.length - 1]
    console.log(`[AI智能回复] 🔍 检查最新评论: "${latestComment.content}" - ${latestComment.nick_name}`)
    
    // 如果是已经处理过的评论，跳过
    if (latestComment.msg_id === lastProcessedCommentIdRef.current) {
      console.log(`[AI智能回复] ⏭️  已处理过此评论，跳过`)
      return
    }

    const content = latestComment.content
    // 使用nick_name作为用户标识（因为评论消息没有user_id字段）
    const userId = latestComment.nick_name
    const username = latestComment.nick_name
    const now = Date.now()

    // 标准化文本：去除常见语气词和标点符号，用于模糊匹配
    const normalizeText = (text: string) => {
      return text
        .replace(/[？?！!。.，,、；;：:""''「」『』（）()【】\[\]《》<>～~…—\-\s]/g, '') // 去除标点和空格
        .replace(/[吧呢啊哦喔嘛哇呀哈咯啦噢唷嗯哼嘿耶]/g, '') // 去除语气词
        .toLowerCase()
    }

    // 检查是否包含触发关键词（使用模糊匹配）
    console.log(`[AI智能回复] 🔑 检查关键词匹配，配置的关键词: ${config.smartReply.keywords.join(', ')}`)
    
    const normalizedContent = normalizeText(content)
    const matchedKeyword = config.smartReply.keywords.find(keyword => {
      const normalizedKeyword = normalizeText(keyword)
      return normalizedContent.includes(normalizedKeyword)
    })
    
    if (!matchedKeyword) {
      console.log(`[AI智能回复] ⏭️  不匹配任何关键词，跳过`)
      return
    }

    logger.info(`✅ 检测到关键词"${matchedKeyword}"，用户：${username}，内容：${content}`)

    // 防重复检查 - 用户间隔
    const userInterval = config.smartReply.deduplication?.userInterval ?? 120
    const lastReplyTime = repliedUsersRef.current.get(userId)
    if (lastReplyTime && (now - lastReplyTime) < userInterval * 1000) {
      const waitSeconds = Math.ceil((userInterval * 1000 - (now - lastReplyTime)) / 1000)
      logger.info(`⏭️ 跳过：用户"${username}"在 ${userInterval} 秒内已回复过（还需等待 ${waitSeconds} 秒）`)
      // 更新最后处理的评论ID，避免重复检查
      lastProcessedCommentIdRef.current = latestComment.msg_id
      return
    }

    // 防重复检查 - 同一用户同一问题间隔
    const questionInterval = config.smartReply.deduplication?.questionInterval ?? 3600
    if (questionInterval > 0) {
      const questionKey = `${userId}_${content}` // 用户昵称 + 问题内容作为唯一标识
      const lastQuestionTime = repliedQuestionsRef.current.get(questionKey)
      if (lastQuestionTime && (now - lastQuestionTime) < questionInterval * 1000) {
        const waitSeconds = Math.ceil((questionInterval * 1000 - (now - lastQuestionTime)) / 1000)
        logger.info(`⏭️ 跳过：用户"${username}"在 ${questionInterval} 秒内已问过相同问题"${content}"（还需等待 ${waitSeconds} 秒）`)
        // 更新最后处理的评论ID
        lastProcessedCommentIdRef.current = latestComment.msg_id
        return
      }
    }

    // 生成AI回复
    try {
      logger.info(`🤖 开始生成AI回复...`)
      
      const apiKey = aiApiKeys[aiConfig.provider]
      if (!apiKey) {
        logger.error('未配置 API Key')
        return
      }

      // 构建系统提示词
      let systemPrompt = '你是一个专业的直播助手，负责回答观众的问题。请用简短、友好的语气回复，不要超过50个字。回复时不要包含观众的昵称，直接回答问题即可。'
      
      if (activeLiveStreamConfig) {
        if (activeLiveStreamConfig.config.role) {
          systemPrompt += `你的角色定位是：${activeLiveStreamConfig.config.role}。`
        }
        if (activeLiveStreamConfig.config.positivePrompt) {
          systemPrompt += `${activeLiveStreamConfig.config.positivePrompt}`
        }
        if (activeLiveStreamConfig.config.negativePrompt) {
          systemPrompt += `注意避免：${activeLiveStreamConfig.config.negativePrompt}`
        }
        if (activeLiveStreamConfig.config.productParams) {
          systemPrompt += `产品信息：${activeLiveStreamConfig.config.productParams}`
        }
      }

      const userPrompt = `观众"${username}"问：${content}\n\n请简短回复问题内容（不超过50字）：`

      const messages = [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userPrompt },
      ]

      // 调用AI API
      const replyContent = await window.ipcRenderer.invoke(
        IPC_CHANNELS.tasks.aiChat.normalChat,
        {
          provider: aiConfig.provider,
          model: aiConfig.model,
          apiKey,
          messages,
          customBaseURL,
        }
      )

      if (!replyContent) {
        throw new Error('AI返回内容为空')
      }
      
      // 在回复内容前加上用户昵称
      const finalReply = `${username}，${replyContent}`
      logger.success(`✅ AI回复生成成功：${finalReply}`)

      // ✅ 修复：将AI智能回复内容加入播放队列
      const provider = config.provider || 'aliyun'
      if (provider === 'aliyun') {
        if (!config.aliyun?.accessKeyId || !config.aliyun?.accessKeySecret || !config.aliyun?.appKey) {
          logger.warn('⚠️ 未配置阿里云TTS')
          return
        }
      } else if (provider === 'tencent') {
        if (!config.tencent?.secretId || !config.tencent?.secretKey) {
          logger.warn('⚠️ 未配置腾讯云TTS')
          return
        }
      }

      const playMode = config.smartReply?.playMode || 'next'
      
      // 发送事件到ContentRewriteCard，让它将内容加入队列
      ;(window.ipcRenderer as any).send('ai-assist:add-to-queue', {
        accountId: currentAccountId,
        type: 'ai_reply' as const,
        originalContent: `${username}: ${content}`,
        rewrittenContent: finalReply,
        playMode,
      })
      
      logger.success(`AI回复已加入队列: ${finalReply}`)

      // 记录已回复（防重复）
      repliedUsersRef.current.set(userId, now)
      logger.info(`📝 已记录用户"${username}"的回复（${userInterval}秒内不会重复回复此用户）`)
      
      const questionInterval = config.smartReply.deduplication?.questionInterval ?? 3600
      if (questionInterval > 0) {
        const questionKey = `${userId}_${content}`
        repliedQuestionsRef.current.set(questionKey, now)
        logger.info(`📝 已记录问题"${content}"（${questionInterval}秒内不会重复回复相同问题）`)
      }
      lastProcessedCommentIdRef.current = latestComment.msg_id

      // 清理过期的用户记录
      for (const [uid, timestamp] of repliedUsersRef.current.entries()) {
        if (now - timestamp > userInterval * 1000) {
          repliedUsersRef.current.delete(uid)
        }
      }

      // 清理过期的问题记录
      if (questionInterval > 0) {
        for (const [key, timestamp] of repliedQuestionsRef.current.entries()) {
          if (now - timestamp > questionInterval * 1000) {
            repliedQuestionsRef.current.delete(key)
          }
        }
      }
    } catch (error) {
      logger.error(`AI回复失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  }, [config, isListening, comments, aiApiKeys, aiConfig, customBaseURL, activeLiveStreamConfig, logger, currentAccountId])

  // 启动定时检测
  useEffect(() => {
    if (!config.smartReply?.enable) {
      if (checkTimerRef.current) {
        clearInterval(checkTimerRef.current)
        checkTimerRef.current = null
        logger.info('❌ AI智能回复已停止（功能未启用）')
      }
      return
    }

    if (isListening !== 'listening') {
      if (checkTimerRef.current) {
        clearInterval(checkTimerRef.current)
        checkTimerRef.current = null
        logger.info('❌ AI智能回复已停止（评论监听未启动）')
      }
      return
    }

    const interval = (config.smartReply.checkInterval ?? 5) * 1000
    console.log(`==========================================`)
    console.log(`[AI智能回复] 🚀 定时检查已启动`)
    console.log(`[AI智能回复] ⏱️  检查间隔: ${config.smartReply.checkInterval ?? 5}秒`)
    console.log(`[AI智能回复] 🔑 监听关键词: ${config.smartReply.keywords?.join(', ')}`)
    console.log(`==========================================`)
    
    logger.info(`✅ AI智能回复已启动，检测间隔：${config.smartReply.checkInterval ?? 5}秒`)

    // 清除之前的定时器
    if (checkTimerRef.current) {
      clearInterval(checkTimerRef.current)
    }

    // 启动定时检测
    checkTimerRef.current = setInterval(() => {
      console.log(`[AI智能回复] ⏰ 定时检查触发 (间隔${config.smartReply.checkInterval ?? 5}秒)`)
      checkAndReply()
    }, interval)

    // 组件卸载时清理
    return () => {
      if (checkTimerRef.current) {
        clearInterval(checkTimerRef.current)
        checkTimerRef.current = null
        logger.info('❌ AI智能回复已停止')
      }
    }
  }, [config.smartReply?.enable, config.smartReply?.checkInterval, isListening, checkAndReply, logger])

  // 不渲染任何UI
  return null
}

